package com.renwei.yunlong.activity.me;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.contacts.CompanyCertificateActivity;
import com.renwei.yunlong.activity.contacts.CompanyCertificateTypeActivity;
import com.renwei.yunlong.activity.work.GuideWebActivity;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CertificateInfoBean;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.FriendEnterpriseBean;
import com.renwei.yunlong.event.MinePageRefreshEvent;
import com.renwei.yunlong.global.EventKey;
import com.renwei.yunlong.global.IntentKey;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 企业认证--页面
 * <p>
 * Created by Administrator on 2017/8/29.
 */

public class EnterpriseCertificationActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {
    private static final String TAG = "EnterpriseCertificationActivity---:";
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_edit)
    TextView tvEdit;
    @Bind(R.id.iv_cont)
    ImageView ivCont;
    @Bind(R.id.iv_edit)
    ImageView ivEdit;
    @Bind(R.id.iv_contacts)
    ImageView ivContacts;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.iv_scroll)
    ImageView ivScroll;
    @Bind(R.id.tv_enterprise_name)
    TextView tvEnterpriseName;
    @Bind(R.id.rl_enterprise_name)
    RelativeLayout rlEnterpriseName;
    @Bind(R.id.tv_email)
    TextView tvEmail;
    @Bind(R.id.rl_email)
    RelativeLayout rlEmail;
    @Bind(R.id.tv_contact)
    TextView tvContact;
    @Bind(R.id.rl_contact)
    RelativeLayout rlContact;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.rl_phone)
    RelativeLayout rlPhone;
    @Bind(R.id.tv_certificate_type)
    TextView tvCertificateType;
    @Bind(R.id.rl_certificate_type)
    RelativeLayout rlCertificateType;
    @Bind(R.id.tv_certificate_number)
    TextView tvCertificateNumber;
    @Bind(R.id.rl_certificate_number)
    RelativeLayout rlCertificateNumber;
    @Bind(R.id.tv_years)
    TextView tvYears;
    @Bind(R.id.rl_years)
    RelativeLayout rlYears;
    @Bind(R.id.tv_photo)
    TextView tvPhoto;
    @Bind(R.id.rl_photo)
    RelativeLayout rlPhoto;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.rl_address)
    RelativeLayout rlAddress;
    @Bind(R.id.tv_certificate)
    TextView tvCertificate;
    @Bind(R.id.rl_certificate)
    RelativeLayout rlCertificate;

    private boolean haveCertificate = false;//是否有证书
    private HashMap companyMap;//提交企业信息的map
    private String certificateType = "31";
    private FriendEnterpriseBean enterpriseBean;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enterprise_certification);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);//订阅
        companyMap = new HashMap();
        initListener();
    }

    //初始化事件
    private void initListener() {
        tvEdit.setText("提交");
        tvTitle.setText("企业认证");
        Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
        titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
        tvTitle.setCompoundDrawables(null, null, titleLeft, null);
        tvTitle.setCompoundDrawablePadding(10);

        ivBack.setVisibility(View.VISIBLE);
        tvEdit.setVisibility(View.VISIBLE);
        tvEdit.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        rlEnterpriseName.setOnClickListener(this);
        rlAddress.setOnClickListener(this);
        rlCertificate.setOnClickListener(this);
        rlCertificateNumber.setOnClickListener(this);
        rlCertificateType.setOnClickListener(this);
        tvTitle.setOnClickListener(this);
        rlYears.setOnClickListener(this);
        rlPhoto.setOnClickListener(this);
        rlPhone.setOnClickListener(this);
        rlEmail.setOnClickListener(this);
        rlContact.setOnClickListener(this);
        rlCertificate.setOnClickListener(this);

        refreshCompanyInfo();
    }

    //初始化数据
    private void initData() {
        if (enterpriseBean != null && enterpriseBean.getRows() != null) {
            //业主
            tvEnterpriseName.setText(StringUtils.value(enterpriseBean.getRows().getCompanyName()));
            tvContact.setText(StringUtils.value(enterpriseBean.getRows().getRegisterName()));//联系人
            tvPhone.setText(StringUtils.value(enterpriseBean.getRows().getCustomerPhone()));//电话
            if ("1".equals(StringUtils.value(enterpriseBean.getRows().getCertificateType()))) {
                tvCertificateType.setText("营业执照");
            } else if ("2".equals(StringUtils.value(enterpriseBean.getRows().getCertificateType()))) {
                tvCertificateType.setText("组织机构代码证");
            }
            tvCertificateNumber.setText(StringUtils.value(enterpriseBean.getRows().getCertificateNumber()));//证件号码
            tvAddress.setText(StringUtils.value(enterpriseBean.getRows().getProvinceId()) + StringUtils.value(enterpriseBean.getRows().getCityId()) + StringUtils.value(enterpriseBean.getRows().getRegionId()) + StringUtils.value(enterpriseBean.getRows().getRegisterAddr()));
            //有效期
            tvYears.setText(StringUtils.value(enterpriseBean.getRows().getEffectiveAge()));
            tvEmail.setText(StringUtils.value(enterpriseBean.getRows().getMail()));
        }


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_title:
                GuideWebActivity.openActivity(this, Api.$().GUIDE_IDENT_COMP_URI);
                break;
            case R.id.iv_back:
                EnterpriseCertificationActivity.this.onBackPressed();
                break;
            case R.id.tv_edit://提交企业信息
                if (TextUtils.isEmpty(tvEnterpriseName.getText())) {
                    showCenterInfoMsg("企业名称不能为空");
                    return;
                }
                if (TextUtils.isEmpty(tvCertificateType.getText())) {
                    showCenterInfoMsg("请选择企业证书类型");
                    return;
                }
                if (TextUtils.isEmpty(tvCertificateNumber.getText())) {
                    showCenterInfoMsg("企业证件号码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(tvAddress.getText())) {
                    showCenterInfoMsg("企业注册地址不能为空");
                    return;
                }
                checkCertificate();//检查证书是否为空
                break;
            case R.id.rl_enterprise_name://企业名称
                jump2EditPage("企业名称", IntentKey.COMPANY_NAME_KEY, 1, IntentKey.COMPANY_NAME, tvEnterpriseName.getText().toString());
                break;
            case R.id.rl_email://企业邮箱
                jump2EditPage("企业邮箱", IntentKey.OFFICE_EMAIL_KEY, 2, IntentKey.OFFICE_EMAIL, tvEmail.getText().toString());
                break;
            case R.id.rl_contact://企业联系人
                jump2EditPage("联系人", IntentKey.COMPANY_LINK_MAN_KEY, 3, IntentKey.COMPANY_LINK_MAN, tvContact.getText().toString());
                break;
            case R.id.rl_phone://企业电话
                jump2EditPage("企业电话", IntentKey.COMPANY_LINK_PHONE_KEY, 4, IntentKey.COMPANY_LINK_PHONE, tvPhone.getText().toString());
                break;
            case R.id.rl_certificate_type://证件类型
                String tempType = "1";
                if ("营业执照".equals(StringUtils.value(tvCertificateType.getText()))) {
                    tempType = "1";
                } else {
                    tempType = "2";
                }
                Intent intent = new Intent(this, CompanyCertificateTypeActivity.class);
                intent.putExtra(IntentKey.CERTIFICATET_TYPE, tempType);
                startActivityForResult(intent, IntentKey.CERTIFICATET_TYPE_KEY);
                break;
            case R.id.rl_certificate_number://证件号码
                jump2EditPage("证件号码", IntentKey.COMPANY_CARD_NUM_KEY, 5, IntentKey.COMPANY_CARD_NUM, tvCertificateNumber.getText().toString());
                break;
            case R.id.rl_years://有效年限
                jump2EditPage("有效年限", IntentKey.COMPANY_YEARS_KEY, 6, IntentKey.COMPANY_YEARS, tvYears.getText().toString());
                break;
            case R.id.rl_photo://证件照片
                Intent photoIntent = new Intent(this, CompanyCertificateActivity.class);
                photoIntent.putExtra("from", "else");
                photoIntent.putExtra("certificateType", certificateType);
                photoIntent.putExtra("title", "证件");
                startActivity(photoIntent);
                break;
            case R.id.rl_address://注册地址
                Intent intentAddress = new Intent(this, RegisterAddressActivity.class);
                String provinceId = "";
                String cityId = "";
                String regionId = "";
                String address = "";
                if ("1".equals(companyType)) {
                    provinceId = StringUtils.value(ownerBean.getRows().getCompany().getProvinceId());
                    cityId = StringUtils.value(ownerBean.getRows().getCompany().getCityId());
                    regionId = StringUtils.value(ownerBean.getRows().getCompany().getRegionId());
                    address = StringUtils.value(ownerBean.getRows().getCompany().getRegisterAddr());
                } else {
                    provinceId = StringUtils.value(serviceLoginBean.getRows().getCompany().getProvinceId());
                    cityId = StringUtils.value(serviceLoginBean.getRows().getCompany().getCityId());
                    regionId = StringUtils.value(serviceLoginBean.getRows().getCompany().getRegionId());
                    address = StringUtils.value(serviceLoginBean.getRows().getCompany().getRegisterAddr());
                }
                intentAddress.putExtra("provinceId", companyMap.get("provinceId") == null ?
                        provinceId : StringUtils.value(companyMap.get("provinceId")));
                intentAddress.putExtra("cityId", companyMap.get("cityId") == null ?
                        cityId : StringUtils.value(companyMap.get("cityId")));
                intentAddress.putExtra("regionId", companyMap.get("regionId") == null ?
                        regionId : StringUtils.value(companyMap.get("regionId")));
                intentAddress.putExtra("detailAddress", companyMap.get("registerAddr") == null ?
                        address : StringUtils.value(companyMap.get("registerAddr")));
                startActivityForResult(intentAddress, 999);
                break;
            case R.id.rl_certificate://资质证书
                Intent certificateIntent = new Intent(this, CompanyCertificateActivity.class);
                certificateIntent.putExtra("from", "else");
                certificateIntent.putExtra("certificateType", "32");
                certificateIntent.putExtra("title", "资质证书");
                startActivity(certificateIntent);
                break;
            default:
                break;
        }
    }

    private void checkCertificate() {
        HashMap queryMap = new HashMap();
        if ("1".equals(companyType)) {
            queryMap.put("companyCode", ownerBean.getRows().getCompany().getCompanyCode());
        } else {
            queryMap.put("companyCode", serviceLoginBean.getRows().getCompany().getCompanyCode());
        }
        queryMap.put("type", certificateType);
        ServiceRequestManager.getManager().QueryCompanyCertificate(this, JsonMapUtil.mapToJson(queryMap), this);
    }


    public void checkAndCommit() {
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        LogUtil.e(TAG + "companyType 提交企业信息 :" + companyType);
        if ("1".equals(YunLongApplication.getCompanyType())) {
            companyMap.put("companyCode", ownerBean.getRows().getCompany().getCompanyCode());
            LogUtil.e(TAG + "提交参数：" + JsonMapUtil.mapToJson(companyMap));
        } else {
            companyMap.put("companyCode", serviceLoginBean.getRows().getCompany().getCompanyCode());
            LogUtil.e(TAG + "提交参数：" + JsonMapUtil.mapToJson(companyMap));
        }
        manager.UpdateCompanyInfo(this, JsonMapUtil.mapToJson(companyMap), this);
    }

    public void jump2EditPage(String title, int key, int extras, String... params) {
        Intent intent = new Intent(this, EditCompanyInfoActivity.class);
        intent.putExtra(IntentKey.TITLE, title);
        intent.putExtra(params[0], params[1]);
        intent.putExtra(IntentKey.COMPANY_INFO_TYPE, extras);
        startActivityForResult(intent, key);
    }


    @Override
    public void onBackPressed() {
        if (companyMap != null && companyMap.size() > 0) {
            DialogUtils.showDialog(this, "您将放弃保存修改后的数据", false, new DialogUtils.OnDialogClickListener() {
                @Override
                public void onCancel(Dialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onConfirm(Dialog dialog) {
                    EnterpriseCertificationActivity.this.finish();
                }
            });
        } else {
            EnterpriseCertificationActivity.this.finish();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case IntentKey.COMPANY_NAME_KEY:
                    companyMap.put(IntentKey.COMPANY_NAME, data.getStringExtra(IntentKey.CONTENT));
                    tvEnterpriseName.setText(StringUtils.value(data.getStringExtra(IntentKey.CONTENT)));
                    break;
                case IntentKey.OFFICE_EMAIL_KEY:
                    companyMap.put(IntentKey.OFFICE_EMAIL, data.getStringExtra(IntentKey.CONTENT));
                    tvEmail.setText(StringUtils.value(data.getStringExtra(IntentKey.CONTENT)));
                    break;
                case IntentKey.COMPANY_LINK_MAN_KEY:
                    companyMap.put(IntentKey.COMPANY_LINK_MAN, data.getStringExtra(IntentKey.CONTENT));
                    tvContact.setText(StringUtils.value(data.getStringExtra(IntentKey.CONTENT)));
                    break;
                case IntentKey.COMPANY_LINK_PHONE_KEY:
                    companyMap.put(IntentKey.COMPANY_LINK_PHONE, data.getStringExtra(IntentKey.CONTENT));
                    tvPhone.setText(StringUtils.value(data.getStringExtra(IntentKey.CONTENT)));
                    break;
                case IntentKey.COMPANY_CARD_NUM_KEY:
                    companyMap.put(IntentKey.COMPANY_CARD_NUM, data.getStringExtra(IntentKey.CONTENT));
                    tvCertificateNumber.setText(StringUtils.value(data.getStringExtra(IntentKey.CONTENT)));
                    break;
                case IntentKey.COMPANY_YEARS_KEY:
                    companyMap.put(IntentKey.COMPANY_YEARS, data.getStringExtra(IntentKey.CONTENT));
                    tvYears.setText(StringUtils.value(data.getStringExtra(IntentKey.CONTENT)));
                    break;
                case IntentKey.CERTIFICATET_TYPE_KEY:
                    companyMap.put(IntentKey.CERTIFICATET_TYPE, data.getStringExtra(IntentKey.CONTENT));
                    String tempType = data.getStringExtra(IntentKey.CONTENT);
                    if ("1".equals(tempType)) {
                        tvCertificateType.setText("营业执照");
                    }
                    if ("2".equals(tempType)) {
                        tvCertificateType.setText("组织机构代码证");
                    }
                    break;
                case 999:
                    String provinceId = StringUtils.value(data.getStringExtra("provinceId"));
                    String cityId = StringUtils.value(data.getStringExtra("cityId"));
                    String regionId = StringUtils.value(data.getStringExtra("regionId"));
                    String registerAddr = StringUtils.value(data.getStringExtra("registerAddr"));
                    String years = StringUtils.value(data.getStringExtra("effectiveAge"));
                    companyMap.put("provinceId", provinceId);
                    companyMap.put("cityId", cityId);
                    companyMap.put("regionId", regionId);
                    companyMap.put("registerAddr", registerAddr);
                    companyMap.put("effectiveAge", years);
                    tvAddress.setText(provinceId + cityId + regionId + registerAddr);
                    break;
                default:
                    break;
            }
            LogUtil.e(TAG + JsonMapUtil.mapToJson(companyMap));
        }
    }


    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 886:
                CommonBean infoBean = new Gson().fromJson(result, CommonBean.class);
                if (infoBean != null && infoBean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("提交成功");
                    refreshCompanyInfo();// 2017/12/11 当信息提交成功之后 请求重新登录获取用户信息
                    this.finish();
                } else {
                    showCenterInfoMsg("提交失败");
                }
                break;
            case 880:
                CertificateInfoBean certificateBean = new Gson().fromJson(result, CertificateInfoBean.class);
                if (certificateBean != null && certificateBean.getRows() != null && certificateBean.getRows().size() > 0) {
                    haveCertificate = true;
                    if (haveCertificate) {
                        if (companyMap != null && companyMap.size() > 0) {
                            DialogUtils.showDialog(this, "您修改了企业信息，是否重新提交审核进入“待审核状态”", false, new DialogUtils.OnDialogClickListener() {
                                @Override
                                public void onCancel(Dialog dialog) {
                                    dialog.dismiss();

                                }

                                @Override
                                public void onConfirm(Dialog dialog) {
                                    dialog.dismiss();
                                    checkAndCommit();
                                }
                            });
                        } else {
                            finish();
                        }
                    } else {
                        showCenterInfoMsg("企业证书不能为空");
                    }
                } else {
                    showCenterInfoMsg("企业证书不能为空");
                    LogUtil.e("读取证书错误" + result);
                    haveCertificate = false;
                }
                break;
            case 879:
                enterpriseBean = new Gson().fromJson(result, FriendEnterpriseBean.class);
                initData();
                break;
            default:
                super.onSuccess(requestId, result);
                break;

        }
    }

    @Override
    public void onException(int requestId, String code) {
        LogUtil.e(code);
        switch (requestId) {
            case 886:
                break;
            case 880:
                haveCertificate = false;
                break;
            default:
                break;


        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEventMessage(MinePageRefreshEvent message) {
        LogUtil.e("接收到相关的event" + message.getMessage());
        switch (message.getMessage()) {
            case EventKey.UPDATE_COMPANY_INFO:
                initData();
                break;
            default:
                break;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//订阅
    }


}
